package com.bojiu.lawsearch.lawsearch.service.impl;

import com.bojiu.lawsearch.lawsearch.mapper.*;
import com.bojiu.lawsearch.lawsearch.model.*;
import com.bojiu.lawsearch.lawsearch.service.BackLawService;
import com.bojiu.lawsearch.lawsearch.util.Constances;
import com.bojiu.lawsearch.lawsearch.util.JsonResult;
import com.bojiu.lawsearch.lawsearch.util.ResultCode;
import com.bojiu.lawsearch.lawsearch.util.UtilTools;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: afdiao
 * @Date：2020/3/5 23:23
 * @Description:
 */
@Service
@Slf4j
public class BackLawServiceImpl implements BackLawService {

    @Autowired
    LawBaseInfoMapper lawBaseInfoMapper;

    @Autowired
    LabelMapper labelMapper;

    @Autowired
    RuleMapper ruleMapper;

    @Autowired
    HelpMapper helpMapper;

    @Autowired
    RuleLabelMapper ruleLabelMapper;

    @Autowired
    ProfessionMapper professionMapper;

    @Autowired
    SearchQuestionMapper searchQuestionMapper;

    @Transactional
    @Override
    public JsonResult insertLawBaseInfo(LawBaseInfo lawBaseInfo) throws Exception {
        //设置删除状态
        lawBaseInfo.setIs_deleted(0);
        //设置点击量为0
        lawBaseInfo.setClickCount(0);
        lawBaseInfoMapper.insertSelective(lawBaseInfo);
        int titleId = lawBaseInfoMapper.getmaxId();
        //处理excel数据
        return handleExcle(lawBaseInfo.getExcelName(), titleId);
    }

    private JsonResult handleExcle(String fileName, int titleId) throws Exception {
        Workbook workbook = new XSSFWorkbook(new File(Constances.STORE_URL + fileName));
        Sheet sheet = workbook.getSheetAt(0);
        for (int i = 1; i < 100000; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                return new JsonResult(ResultCode.SUCCESS);
            }
            //
            Cell ruleCell = row.getCell(0);
            if (ruleCell == null || StringUtils.isEmpty(ruleCell.getStringCellValue())) {
                return new JsonResult(ResultCode.SUCCESS);
            }
            Rule rule = new Rule();
            rule.setTitleId(titleId);
            rule.setBody(ruleCell.getStringCellValue());
            //设置默认收藏数
            rule.setCollectCount(0);
            ruleMapper.insertSelective(rule);

            int ruleId = ruleMapper.getMaxId();
            //开始关联标签
            Cell labelCell = row.getCell(1);
            if (labelCell == null) {
                return new JsonResult(ResultCode.SUCCESS);
            }
            String labelValue = labelCell.getStringCellValue();
            Label label = (Label) labelMapper.selectOneByExample(UtilTools.createExampleByKey("name", labelValue, Label.class));
            Integer labelId = label.getId();

            Cell labelValueCell = row.getCell(2);
            if (labelValueCell == null) {
                return new JsonResult(ResultCode.SUCCESS);
            }
            String stringCellValue = labelValueCell.getStringCellValue();
            for (String value : stringCellValue.split("、")) {
                RuleLabel ruleLabel = new RuleLabel();
                ruleLabel.setLabel(value);
                ruleLabel.setLableId(labelId);
                ruleLabel.setRules_id(ruleId);
                //该标签个数默认为1
                ruleLabel.setCount(1);
                ruleLabelMapper.insertSelective(ruleLabel);
            }
        }
        return new JsonResult(ResultCode.SUCCESS);
    }

    @Override
    public Page<LawBaseInfo> getBaseInfoList(String name, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize, true);
        List<LawBaseInfo> lawBaseInfoList = lawBaseInfoMapper.getLawBaseInfoList(name);
        for (LawBaseInfo lawBaseInfo : lawBaseInfoList) {
            //设置类别名称
            String typeName = lawBaseInfo.getType() == 0 ? "法律文件" : "规范标准";
            lawBaseInfo.setTypeName(typeName);
            //设置行业名称
            if (null != lawBaseInfo.getProfession_id()) {
                Profession profession = (Profession) professionMapper.selectOneByExample(UtilTools.createExampleByKey("id", lawBaseInfo.getProfession_id(), Profession.class));
                lawBaseInfo.setProfessionName(profession.getName());
            }
            //设置省份跟市
            if ("all".equals(lawBaseInfo.getProvince())) {
                lawBaseInfo.setProvince("全国");
            }
            if ("all".equals(lawBaseInfo.getCity())) {
                lawBaseInfo.setCity(null);
            }
        }
        PageInfo pageInfo = new PageInfo(lawBaseInfoList);
        Page page = new Page(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getPages(), pageInfo.getTotal(), lawBaseInfoList);
        return page;
    }

    @Override
    public void deleteBaseInfo(int id) {
        LawBaseInfo lawBaseInfo = new LawBaseInfo();
        lawBaseInfo.setIs_deleted(1);
        lawBaseInfoMapper.updateByExampleSelective(lawBaseInfo, UtilTools.createExampleByKey("id", id, LawBaseInfo.class));
    }

    @Override
    public void UpdateBaseInfo(LawBaseInfo lawBaseInfo, int id) {
        lawBaseInfoMapper.updateByExampleSelective(lawBaseInfo, UtilTools.createExampleByKey("id", id, LawBaseInfo.class));
    }

    @Override
    public List<Rule> getRuleList(int titleId) {
        List<Rule> rules = ruleMapper.selectByExample(UtilTools.createExampleByKey("titleId", titleId, Rule.class));
        for (Rule rule : rules) {
            List<RuleLabel> ruleLabels = ruleLabelMapper.selectByExample(UtilTools.createExampleByKey("rules_id", rule.getId(), RuleLabel.class));
            Label label = (Label) labelMapper.selectOneByExample(UtilTools.createExampleByKey("id", ruleLabels.get(0).getLableId(), Label.class));
            StringBuffer stringBuffer = new StringBuffer();
            for (RuleLabel la : ruleLabels) {
                stringBuffer.append(la.getLabel()).append("、");
            }
            String substring = stringBuffer.substring(0, stringBuffer.length() - 1);
            rule.setPrivate_Label(substring);
            rule.setLabelName(label.getName());
        }
        return rules;
    }

    @Override
    public JsonResult addRuleLabel(int ruleId, String label) {
        Map<String, Object> findMap = new HashMap<>();
        findMap.put("rules_id", ruleId);
        findMap.put("label", label);
        if (ruleLabelMapper.selectCountByExample(UtilTools.createExampleByMap(findMap, RuleLabel.class)) > 0) {
            log.error("该标签已经存在");
            return new JsonResult(ResultCode.SAME_DATA);
        }
        List<RuleLabel> ruleLabels = ruleLabelMapper.selectByExample(UtilTools.createExampleByKey("rules_id", ruleId, RuleLabel.class));
        RuleLabel ruleLabel = new RuleLabel();
        ruleLabel.setRules_id(ruleId);
        ruleLabel.setLabel(label);
        //默认设置个数为1
        ruleLabel.setCount(1);
        ruleLabel.setLableId(ruleLabels.get(0).getLableId());
        ruleLabelMapper.insertSelective(ruleLabel);
        return new JsonResult(ResultCode.SUCCESS);
    }

    @Override
    public Page<SearchQuestion> getSearchQuestion(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize, true);
        List<SearchQuestion> searchQuestions = searchQuestionMapper.selectAll();
        PageInfo pageInfo = new PageInfo(searchQuestions);
        Page page = new Page(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getPages(), pageInfo.getTotal(), searchQuestions);
        return page;
    }

    @Override
    public JsonResult updateRuleContent(int ruleId, String content) {
        Rule rule = new Rule();
        rule.setId(ruleId);
        rule.setBody(content);
        ruleMapper.updateByPrimaryKeySelective(rule);
        return new JsonResult(ResultCode.SUCCESS);
    }


    @Override
    public Help getHelpPage() {
        Help help = new Help();
        help.setId(1);
        Help result = (Help) helpMapper.selectOne(help);
        return result;
    }


    @Override
    public JsonResult updateHelpPage(String content) {
        Help help = new Help();
        help.setId(1);
        help.setContent(content);
        int count = helpMapper.updateByPrimaryKey(help);
        return new JsonResult(ResultCode.SUCCESS);
    }
}
